import COS from "cos-js-sdk-v5";

const cos = new COS({
  SecretId: 'AKID4zjNuERSEn7C2mJdjgPtBE1c1CNiqmY7', // 身份识别 ID
  SecretKey: 'RfgT5VjmdJqERP9i4Tq1zlMn25yiKn4A', // 身份密钥
});

const uploadFileToBucket = (file, sccuess, fail, handleUploadProgress) => {
  cos.putObject(
    {
      Bucket: 'record-1331799847', /* 必须 */
      Region: 'ap-chengdu',     /* 存储桶所在地域，必须字段 */
      Key: `event/${new Date().getTime()}_${(Math.random()*10+'').slice(2,9)}.${getExtension(file.name)}`,              /* 必须 */
      Body: file, // 上传文件对象
      onProgress: function(progressData) {
        handleUploadProgress && handleUploadProgress(progressData);
      }
    }, 
    function(err, data) {
      if (data.statusCode === 200) {
        sccuess && sccuess('https://' + data.Location)
      } else {
        fail && fail(err)
      }
    }
  );
}

const getExtension = (name) => {
  return name.substring(name.lastIndexOf(".")+1)
}

export {
  uploadFileToBucket
} 